package id

import (
	"github.com/bwmarrin/snowflake"
	"github.com/google/uuid"
	"langtu.com/common"
	"sync"
)

// myId
// @Description:  id信息
type myId struct {

	//	节点map
	snowflakeNodeMap map[int64]*snowflake.Node
}

var (
	id     *myId
	idOnce sync.Once
)

// NewMyId
//
//	@Description: 新建IdFactory
//	@return *myId
func NewMyId() *myId {
	idOnce.Do(func() {
		snowflakeNodeMap := make(map[int64]*snowflake.Node)
		for i := int64(0); i < 1024; i++ {
			snowflakeNodeMap[i], _ = snowflake.NewNode(i)
		}
		id = &myId{snowflakeNodeMap: snowflakeNodeMap}
	},
	)
	return id
}

// NextUuidId
//
//	@Description: 	新建uuid密码
//	@receiver idFactory
//	@return string
func (id *myId) NextUuidId() string {
	return uuid.NewString()
}

// NextSnowflakeId
//
//	@Description: 	新建雪花算法获取的snowflake的id
//	@receiver idFactory
//	@return int64
func (id *myId) NextSnowflakeId(nodeId int64) (int64, error) {
	if nodeId <= 0 || nodeId > 1024 {
		return 0, &common.IllegalArgumentError{Message: "nodeId必须是0~2024"}
	}
	return id.snowflakeNodeMap[nodeId].Generate().Int64(), nil
}
